package com.donleo.stmg.utils;

import com.donleo.stmg.entity.vo.PermissionVo;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liangd
 * date 2020-12-23 16:19
 * code 生成树工具类
 */
public class TreeUtil {

    private List<PermissionVo> menuCommon;

    /**
     * service层调用的方法,并将数据以list的形式返回
     *
     * @param menu 菜单集合
     * @return list
     */
    public List<Object> menuList(List<PermissionVo> menu) {
        this.menuCommon = menu;
        List<Object> list = new ArrayList<>();
        for (PermissionVo ps : menu) {
            Map<String, Object> map = new LinkedHashMap<>();
            //判断根节点是否是0
            if (ps.getPid().equals(0)) {
                setTreeData(map, ps);
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 不判断根节点遍历
     *
     * @param pList
     * @return
     */
    public List<Object> userMenuList(List<PermissionVo> pList) {
        this.menuCommon = pList;
        List<Object> list = new ArrayList<>();
        for (PermissionVo ps : pList) {
            Map<String, Object> map = new LinkedHashMap<>();
            setTreeData(map, ps);
            list.add(map);
        }
        return list;
    }

    /**
     * 子集查找遍历
     * 递归遍历，直到没有子节点为止
     *
     * @param id 父id
     * @return list
     */
    private List<Object> menuChild(Integer id) {
        List<Object> list = new ArrayList<>();
        for (PermissionVo ps : menuCommon) {
            Map<String, Object> map = new LinkedHashMap<>();
            if (ps.getPid().equals(id)) {
                setTreeData(map, ps);
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 赋值
     * id  当前id
     * title 标题
     * field 权限值
     * href 跳转路径
     * children 子节点数据
     */
    private void setTreeData(Map<String, Object> map, PermissionVo ps) {
        map.put("id", ps.getId());
        map.put("title", ps.getName());
        map.put("field", ps.getValue());
        map.put("href", ps.getUri());
        map.put("children", menuChild(ps.getId()));
    }


}
